"""
Author: wenbin
Create: 2024-08-19
"""
from dataclasses import dataclass
from enum import IntEnum, unique
from typing import Any

from flask import jsonify, make_response, Response


@unique
class ResponseCode(IntEnum):
    """
    响应状态码
    """
    SUCCESS = 0  # 成功
    FAIL = -1  # 失败


@dataclass
class ApiResponse:
    """
    统一响应格式
    """
    code: int
    message: str
    data: Any | None = None

    @staticmethod
    def success(code: int = ResponseCode.SUCCESS.value, message: str = "成功", data: Any = None,
                status_code: int = 200) -> Response:
        """
        成功

        :param code:响应状态码
        :param data: 数据
        :param message: 提示信息
        :param status_code: HTTP 状态码
        :return: json
        """
        return _make_response(ApiResponse(code, message, data), status_code)

    @staticmethod
    def fail(code: int = ResponseCode.FAIL.value, message: str = "失败", status_code: int = 200) -> Response:
        """
        失败

        :param code: 响应状态码
        :param message: 提示信息
        :param status_code: HTTP 状态码
        :return: json
        """
        return _make_response(ApiResponse(code, message=message, data=None), status_code)


def _make_response(response: ApiResponse, status_code: int) -> Response:
    """
    构建响应对象

    :param response: 响应对象
    :param status_code: 状态码
    :return: 构建响应对象
    """
    return make_response(jsonify(response), status_code)
